//页面加载完成，赋予事件，代码先放到这个js文件中(js代码存放位置统一规划)
//其它出入库对应功能代码，内部逻辑仅仅调整 datagrid虚拟视图部分取值逻辑
$(function(){
	//统一数量，统一折扣js
	$('input[extendType="unifiedEvent"]').on('keyup',function(event){
		var options={
				datagrid:'list_datagrid_table',
				fieldName:'productQuantity'
		};
		var extendOptions=eval('('+$(this).attr('extendOptions')+')');
		var setting=$.extend(options,extendOptions);
		var key = event.which;
		var KEY_ENTER = 13;
		var value = $(this).val();
		if(key == KEY_ENTER){
			if(isNull(value)){
				return;
			}
			if(value < 0){
				return;
			}
            var opts=$("#"+setting.datagrid).datagrid('options');
            var data=$("#"+setting.datagrid).datagrid('getData');
            var rows=data.rows;  
            if(opts.view.type == 'scrollview'){
               var firstRrows=data.firstRows;
                if(firstRrows.length>0){
                	rows=firstRrows;
                }
            }
			for(var i = 0; i < rows.length; i++){
				rows[i][setting.fieldName] = value;
			}
			$("#"+setting.datagrid).datagrid("loadData",rows);
		}else{
			//这部分代码结构还有优化空间
			if(setting.ruleType=='quantity'){
				var numberArray = value.match(/(\d+(\.\d+)?)/g);
				var finalValue = "";
				for(var i = 0; i < numberArray.length; i++){
					finalValue+=numberArray[i];
				}
				$(this).val(finalValue);
			}else if (setting.ruleType=='discount'){
				var numberArray = value.match(/(1)|((0(\.\d+)?)|((\.)?))/g);
				var finalValue = "";
				for(var i = 0; i < numberArray.length; i++){
					finalValue+=numberArray[i];
				}
				if(Number(finalValue)>1){
					$(this).val(1);
				}else{
					$(this).val(finalValue);
				}
			}
		}
	});
	//删除功能
	$('button[extendType="deleteEvent"],a[extendType="deleteEvent"]').on('click',function(e){
		var options={
				datagrid:'list_datagrid_table'
		};
		var extendOptions=eval('('+$(this).attr('extendOptions')+')');
		var setting=$.extend(options,extendOptions);
		var rows = $("#"+setting.datagrid).datagrid('getSelections'); 
	    if(rows.length < 1){
	    	var options = {
	            title: "系统提示",
	            msg: "请至少选择一条数据!",
	            showType: 'slide',
	            timeout: 2000
	        };
	        $.messager.show(options);
	    	return false;
	    }
	    $.messager.confirm("操作提示", "是否确定删除所有选定项？", function (data) {
	        if (data) {
	        	$("#"+setting.datagrid).datagrid({url:''});
	        	//判断删除全部
	        	var checked=$('.datagrid-header-check input:checked').val();
	    		if('on'==checked){
	    			$("#"+setting.datagrid).datagrid("loadData",[]);
	    		}else{
		            var allRows;
		            var opts=$("#"+setting.datagrid).datagrid('options');
		            var data=$("#"+setting.datagrid).datagrid('getData');
		            allRows=data.rows;
		            if(opts.view.type == 'scrollview'){
		            	var firstRows=data.firstRows;
		            	if(firstRows.length>0){
		            		allRows=firstRows;
		            	}
		            }
		            var newDataArray = new Array();
		            var arrayIndex = 0;
		            //这部分逻辑可以优化20160127 zhanghuajie
		            for(var j = 0; j < allRows.length; j++){
		            	var has = false;
		            	var index1 = $("#"+setting.datagrid).datagrid('getRowIndex', allRows[j]); 
		            	for(var i = 0; i < rows.length; i++){
		    				var index2 = $("#"+setting.datagrid).datagrid('getRowIndex', rows[i]);  
		    				if(index1==index2){
		    					has = true;
		    					break;
		    				} 
		    			}
		            	if(!has){
		                	newDataArray[arrayIndex++]=allRows[j];
		            	}
		            }
		            $("#"+setting.datagrid).datagrid("loadData",newDataArray);
		        }
	        }
	        else {
	           return false;
	        }
	    });
	});
	//选择弹出框功能
	$('button[extendType="selectEvent"],a[extendType="selectEvent"]').on('click',function(e){
		var options=$(this).attr('extendOptions') || $(this).prev().attr('oasisOptions');
		if(options){
			OasisHelper.openSelector(eval('('+options+')'));
		}else{
			$.messager.alert('error','查询异常（未配置参数），请联系管理员！');
		}
		
	});	
	//通用选择器按键事件绑定
	$(document).on('keyup', 'input[oasisType="selector"]', function (e) {
	    var key = e.which;
	    var obj = this;
	    if (key == 13) {
	    	var inputObj = obj;
	        var curSelectorInput = $(this);
	        var searchValue = $(this).val();
	        var oasisOptions = $(this).attr("oasisOptions");
	        var options = eval('(' + oasisOptions + ')');
	        console.log(options);
	        var isOpenSelector = true;
	        if (searchValue != '' && options != '') {
	            $(this).attr('disabled', true);
	            var parentWidth = 0;
	            var parentHeight = 0;
	            if(options.width && options.height){
	            	parentWidth = options.width;
	            	parentHeight = options.height;
	            	//options.width = 800;
	            	//options.height = 500;
	            }
	            var defaults = {'width': 800, 'height': 500, 'callBack': $.noop(), 'urlparams': '','noDataMsg':'未查询到数据，请重新录入查询条件！'};
	            var settings = $.extend({}, defaults, options);
	            var urlparams = settings['urlparams'];
	            var id = settings['id'];
	            var width=defaults['width'];
	            var callBackjs = settings['callBack'];
	            var params={};
	            params['oasis_search_fuzzy']=searchValue;
	            //弹出前添加判断是否继续  20160921 
	            var beforeKeySelectCallBack=settings['beforeSelect'];
	            if(beforeKeySelectCallBack && (typeof beforeKeySelectCallBack == "function")){
	             	var beforeEnterFlag = beforeKeySelectCallBack.call(beforeKeySelectCallBack);
	             	if(!beforeEnterFlag){
	             		$(this).attr('disabled', false);
	             		return ;
	             	}
	            }
	            
	            var callBackParams = settings['callBackParams'];
	            var paramObject = {};
	            if(callBackParams && (typeof callBackParams == "function")){
	            	paramObject=callBackParams.call(callBackParams);
	            }
	            for(var key in  paramObject){
	            	params[key]=paramObject[key];
	            }
	            var noDataMsg=settings['noDataMsg'];
	            $.ajax({
	                type: "post",// 
	                dataType: "json",// 返回json格式的数据
	                url: BASE_PATH + '/dictionaryController/quickSearch?id=' + id,// 要访问的后台地址
	                data: params,
	                success: function (data) {// msg为返回的数据，在这里做数据绑定
	                    $(curSelectorInput).removeAttr('disabled');
	                    if (data.rs == 1) {
	                        callBackjs.call(callBackjs, data.datas, callBackParams);
	                    } else if (data.rs == 0) {
	                        jQuery.messager.alert('提示:',noDataMsg);
	                    } else if (data.rs == 2) {
	                    	options.urlparams = params;
	                    	options.callBackParams=undefined;
	                    	if(parentWidth > 0 && parentHeight > 0){
	                    		if(typeof window.parent.changeIframeSize == "function"){
	                        		window.parent.changeIframeSize(parentWidth, parentHeight, $(inputObj).attr('id'));
	                    		}
	                    	}
	                        OasisHelper.openSelector(options);
	                    } else {
	                        alert('请通知管理员，查询错误！');
	                    }
	                },
	                error: function () {
	                    $(curSelectorInput).removeAttr('disabled');
	                    alert('请通知管理员，查询错误！');
	                }
	            });
	        }
	    }
	});
});
//参考代码，
function _10a(_10b){
	var _10c=$.data(_10b,"datagrid");
	var opts=_10c.options;
	var data=_10c.data;
	if(opts.idField){
	return _10c.selectedRows;
	}else{
	var rows=[];
	opts.finder.getTr(_10b,"","selected",2).each(function(){
	rows.push(opts.finder.getRow(_10b,$(this)));
	});
	return rows;
	}
	};
/**
 * helper 工具类 redis缓存数据读取
 */
var OasisHelper = {
    getNameById: function (id) {
        var result = null;
        if (id == null || id == '' || (typeof id) == 'undefined') {
            return '';
        }

        redisDataLoader({},
        	BASE_PATH + '/commonController/getValue/' + id,
            function (data) {
                result = data;
            },
            function () {
                console.log('根据ID跨域查询NAME失败');
            }
        );

        return (result != null) ? result : '';

    },
    getNameByLookupCode: function (lookupCode) {
        var result = null;
        if (lookupCode == null || lookupCode == '' || (typeof lookupCode) == 'undefined') {
            return '';
        }

        redisDataLoader({},
        	BASE_PATH + '/commonController/lookupCodeName/' + lookupCode,
            function (data) {
                result = data;
            },
            function () {
                console.log('根据ID跨域查询NAME失败');
            }
        );

        return (result != null) ? result : '';

    },
    getNameByCode: function (code) {
        var result = null;
        if (code == null || code == '' || (typeof code) == 'undefined') {
            return '';
        }

        redisDataLoader({},
        	BASE_PATH + '/commonController/lookupCodeName/' + code,
            function (data) {
                result = data;
            },
            function () {
                console.log('根据ID跨域查询NAME失败');
            }
        );

        return (result != null) ? result : '';

    },
    initDatagridTip:function(tipInfoArray,datagridId){//初始化datagrid的弹出提示框
    	//var tipInfoArray=[{'field':'code','content':codeTipInfo},{'field':'verifyStatus','content':'22222'}];
    	if(!datagridId){
    		datagridId="datagrid_table";
    	}
    	var $targetHeads=$("#"+datagridId).prev().find(".datagrid-header .datagrid-header-row");
    	for(var i=0;i<tipInfoArray.length;i++){
 			var field=tipInfoArray[i].field;
 			var content=tipInfoArray[i].content;
 			var tipCode=tipInfoArray[i].tipCode;
 			if(!content && tipCode){
 				content=TIP_INFO_MAP[tipCode];
 			}
 			var $targetTd=$targetHeads.find("td[field="+field+"]");
	 		$targetTd.tooltip({
				content:content,
				position:'top',
				onShow:function(){
					$(this).tooltip('tip').css({backgroundColor: '#F7F709',borderColor: '#F7F709'});
				}
				});
 		}
    },
    loadRelationData:function(options){//加载下级下拉菜单数据
    	 //下面这部分可能报空指针异常
    	 var $this=$(this);
    	 var defaults = {
					value:'',//下拉框值
					targetComboboxId:'',//目标下拉框id
		    		firstItem:'Y'
    	        };
    	var settings = $.extend({}, defaults, options);
    	if(!settings['value']){
    		settings['value']=$this.combobox("getValue");
    	}
    	//没有传目标下拉框的值，取下个元素的id
    	if(!settings['targetComboboxId']){
    		 var $target=$this.parent().parent().next().find(".easyui-combobox");
    		 settings['targetComboboxId']=$target.attr('id');
    	}
    	var $target=$("#"+settings['targetComboboxId']);
    	var defaultTargetComboboxParams={'textField':'name','valueField':$target.attr('comboname')};
    	var realTargetComboboxParams={};
    	var targetOptions=$target.attr("data-options");
    	if(!isNull(targetOptions)){
    		targetOptions = eval("({"+targetOptions+"})");
		}else{
			targetOptions = {};
		}
    	var valueField=targetOptions.valueField;
    	var textField=targetOptions.textField;
    	if(valueField && valueField!="value"){
    		realTargetComboboxParams['valueField']=valueField;
   	 	}
    	if(textField && textField!="text"){
    		realTargetComboboxParams['textField']=textField;
   	 	}
    	if($target.attr('firstItem')){
    		settings['firstItem']=$target.attr('firstItem');
    	}
    	$.extend(settings, defaultTargetComboboxParams, realTargetComboboxParams);
    	if('cbb_all'==settings['value']){
    		var datas=[];
    		if('Y'== settings['firstItem']){
        		var firstItems={};
        		firstItems[settings['valueField']]='cbb_all';
        		firstItems[settings['textField']]='全部';
        		datas.push(firstItems);
        	}
    		$("#"+settings['targetComboboxId']).combobox({    
    		    valueField:settings['valueField'],    
    		    textField:settings['textField'],
    		    data:datas,
    		    onLoadSuccess:function(){
    		    	var datas=$(this).combobox("getData");
    		    	if(datas.length>0){
    		    		$(this).combobox('select',datas[0][settings['valueField']]);
    		    	}
    		    	
    		    }
    		}); 
    	}else{
    		 var url=BASE_PATH + '/commonController/nextLevelValues/' + settings['value'];
	    	 $.ajax({
	    	        url: url,
	    	        type:'post',
	    	        dataType: 'json',
	    	        success: function (datas) {
	    	        	if('Y'== settings['firstItem']){
	    	        		var firstItems={};
	    	        		firstItems[settings['valueField']]='cbb_all';
	    	        		firstItems[settings['textField']]='全部';
	    	        		datas.splice(0,0,firstItems);
	    	        	}
	    	        	$("#"+settings['targetComboboxId']).combobox({    
	    	    		    valueField:settings['valueField'],    
	    	    		    textField:settings['textField'],
	    	    		    data:datas,
	    	    		    onLoadSuccess:function(){
	    	    		    	var datas=$(this).combobox("getData");
	    	    		    	if(datas.length>0){
	    	    		    		$(this).combobox('select',datas[0][settings['valueField']]);
	    	    		    	}
	    	    		    	
	    	    		    }
	    	    		}); 
	    	        },
	    	        error: function () {
	    	            console.log("加载失败");
	    	            error.apply(this, arguments);
	    	        }
	    	    });
    	}
    },
    selectFirstItemForCombobox:function(){//选中第一个元素
    	var datas=$(this).combobox("getData");
    	if(datas.length>0){
    		var options=$(this).combobox('options');
    		$(this).combobox('unselect',datas[0][options.valueField]);
			$(this).combobox('select',datas[0][options.valueField]);
    	}
    },
    resizeOrderListDatagrid:function(options){//单据详情页datagrid搞定自适应,仅仅支持单据详情页形式
    	var setting={
    				'datagridId':'list_datagrid_table',
    				'errorHeight':130
    				};
    	$.extend(setting,options);
    	var minHeight=280;
    	var titleHeight = 0;
    	var title = $(".widget-header");
    	if(title.length>0){
    		titleHeight = $(title[0]).height()*title.length;
    	}
    	var toolbarHeight = $("#list_datagrid_toolbar").height();
    	var btnsHeight = $("#btns").height()+10;
    	var bodysHeight=0;
    	$(".widget-body:visible:not(:last)").each(function(){
    		bodysHeight+=$(this).height()+24;
    	});
    	//alert(";;$(window.parent.document).height()"+$(window.parent.document).height());
    	var h = Number($(window.parent.document).height())-(toolbarHeight+btnsHeight+titleHeight+bodysHeight+setting['errorHeight']);
    	//alert("明细"+toolbarHeight+'--'+btnsHeight+'--'+titleHeight+'--'+bodysHeight);
    	if(h<=100){
    		h=minHeight;
    	}
    	$('#'+setting['datagridId']).datagrid('resize', {
    		height:h
    	});
    },
    formNotNullVerify:function(options){//支持form表单的非空验证
    	var result=true;
    	//formId可以不传，默认值是：data_form
    	var setting={'formId':'data_form'};
    	$.extend(setting,options);
    	var $fonts=$("#"+setting['formId']+" div.form-group label font");
    	for(var i=0;i<$fonts.length;i++){
    		var currentValue='';
    		var $forcusInput='';
    		var $this=$($fonts[i]);
    		var $next=$this.parent().next();
    		if($next.has('.easyui-datebox').length>0){
    			currentValue=$next.find('.easyui-datebox').datebox('getValue');
    			$forcusInput=$next.find('span:input:first');
    		}else if($next.has('.easyui-combobox').length>0){
    			currentValue=$next.find('.easyui-combobox').combobox('getValues');
    			$forcusInput=$next.find(':input:first');
    		}else if($next.has('.choose-input').length>0){
    			$forcusInput=$next.find('.choose-input');
    			currentValue=$forcusInput.val();
    		}else{
    			currentValue=$next.find(":input:first").val();
    			$forcusInput=$next.find(":input:first");
    		}
    		if(!currentValue || currentValue==''){
    			$.messager.alert("系统提示","保存失败！"+$this.text().replace('：*','')+"带*不允许为空,请填写",'error',function(){
    				//日期元素暂不支持 获取焦点
    				$forcusInput.focus();
    			});
    			$.plugin.close();
    			result= false;
    			break;
    		}
    	}
    	return result;
    	
    },
    form2object:function(formId){//返回form表单数据
    	formId= formId || "data_form";
    	var obj = {};
	    var formItemStr = $("#"+formId).serialize();
	    formItemStr = decodeURIComponent(formItemStr,true);
	    formItemStr = formItemStr.replace(/\+/g," ");//liulx 16.10.14替换空格变加号
	    var arr = formItemStr.split('&');
	    for(var i=0;i<arr.length;i++){
	    	var keyValues=arr[i].split('=');
	    	var key=keyValues[0];
	    	var value=keyValues[1];
	    	if(key.indexOf("search_")==0){
	    		key=key.substring("search_".length)
			}
	    	if(value=="cbb_all"){
	    		value='';
	    	}
	    	if(value){
	    		obj[key]=value;
	    	}
	    }
	    return obj;
    },
    openSelectorStatus: false,
    openSelector :function(options){
        if (OasisHelper.openSelectorStatus == false) {
            OasisHelper.openSelectorStatus = true;
        } else {
            return;
        }
        var width = 800;
        var height = 500;
        if(!isNull(options.width)){
        	width = options.width
        }
        if(!isNull(options.height)){
        	height = options.height;
        }
        //,multiple:false 默认参数去掉，如果有特殊配置，单独传参
        // 20160313 添加参数对现有逻辑产生影响
        var defaults = {
			width: width, 
			height: height, 
			callBack: $.noop(), 
			urlparams: '',
			afterConfirmClose: 'N',
			otherButtons: [],
			enter:false,
			showLabel:false,//是否显示已选标签
			primaryField:null,//数据列表ID字段
			nameField:null,//数据名称字段
			selected:{}//已选则的数据JSON数组{id:[]数据ID数组,name:[]数据名称数组}
        };
        var settings = $.extend({}, defaults, options);
        
        var beforeSelectCallBack=settings['beforeSelect'];
        if(beforeSelectCallBack){
        	var openFlag=beforeSelectCallBack.call(beforeSelectCallBack);
        	if(!openFlag){
        		return ;
        	}
        }
        var id = settings['id'];
        var title = settings['title'];
        var dg_width = settings['width'];
        var dg_height = settings['height'];
        var callBackjs = settings['callBack'];
        var multiple = settings['multiple'];
        var urlparams = settings['urlparams'];
        var enter = settings['enter'];
        var selected = settings['selected'];
        var showLabel = settings['showLabel'];
        var primaryField = settings['primaryField'];
        var nameField = settings['nameField'];
        //其他按钮，可以是多个，以数组的形式存在，属性有{text:"按钮名称",index:按钮位置(从0开始),handler:function(选择的数据,对话框对象)}
        var otherButtons = settings['otherButtons'];
        var top = settings['top'];
        if(isNull(top)){
        	top = $(document).scrollTop() + 10;
        }
        var params='';
        var resultParams={};
        if(urlparams){
        	$.extend(resultParams,urlparams);
        	for(var key in urlparams){
        		params+='&'+key+"="+urlparams[key];
        	}
        }
        var callBackParams = settings['callBackParams'];
        if(callBackParams){
        	 var paramObject=callBackParams.call(callBackParams);
        	 $.extend(resultParams,paramObject);
             for(var key in  paramObject){
             	params+='&'+key+"="+encodeURIComponent(paramObject[key]);
             }
        }
        params+="&multiple="+multiple+"&selected="+encodeURIComponent(JSON.stringify(selected));
        if(null != primaryField){
        	params+="&primaryField="+primaryField;
        }
        if(null != nameField){
        	params+="&nameField="+nameField;
        }
        params+="&showLabel="+showLabel;
//        params=$.param(resultParams);
        $('#openDictionaryId').parent().remove();
        var url = BASE_PATH + '/dictionaryController/toListPage?id=' + id+'&'+params;
        var dictionaryDiv = '<div id="openDictionaryId" class="easyui-dialog" closed="true" modal="true" ><iframe scrolling="no" id="openDictionaryFrameId" name="openDictionaryFrameId" frameborder="0"   style="width:100%;height:98%;"></iframe></div>';
        $(document.body).append(dictionaryDiv);
        
        var buttons = [{
            id: 'confirm',
            text: '确定',
            handler: function () {
                var jsonData = openDictionaryFrameId.getDictionarySelections();
               // openDictionaryFrameId.clearDataGridSelected();
                if (jsonData != '') {
                	//if(document.getElementById('openDictionaryFrameId') && typeof document.getElementById('openDictionaryFrameId').contentWindow.showCoverLayerByChildren == 'function'){
                	//	document.getElementById('openDictionaryFrameId').contentWindow.showCoverLayerByChildren('请稍等...');
                	//}
                    callBackjs.call(callBackjs, jsonData);
                    if(settings['afterConfirmClose']=='Y'){
                    	$('#openDictionaryId').dialog('close');
                    	 OasisHelper.openSelectorStatus = false;
                    }
                }
                
            }
        }, {
        	id:'closeDictionary',
            text: '关闭',
            handler: function () {
                $('#openDictionaryId').dialog('close');
                //$('#openDictionaryId').parent().remove();
                OasisHelper.openSelectorStatus = false;
                try {
                    //eval('cancelCallBack()'); //弹出框关闭回调事件！！！
                } catch (e) {
                	//alert('error');
                }
            }
        }];
        //覆盖其他按钮的handler方法(xuzhen 20160316)
        for(var i = 0; i < otherButtons.length; i++){
        	var oldHandler = otherButtons[i].handler;
        	if(typeof oldHandler == "function"){
        		otherButtons[i].handler = function(){
        			var jsonData = openDictionaryFrameId.getDictionarySelections();
        			oldHandler.call(oldHandler,jsonData,"#openDictionaryId");
        		}
        	}
        	//插入其他按钮到指定位置(xuzhen 20160316)
        	var index = otherButtons[i].index;
        	if(!isNull(index) && index < buttons.length){
        		buttons.splice(index,0,otherButtons[i]);
        	}
        }
//        buttons = buttons.concat(otherButtons);
        $('#openDictionaryId').dialog({
            collapsible: false,
            minimizable: false,
            maximizable: false,
            resizable: false,
            draggable: true,
            inline: true,
            shadow: false,
            title: title,
            width: dg_width,
            height: dg_height,
            top: top,
            modal: true,
            onClose: function () {
            	//$('#openDictionaryId').parent().remove();
                OasisHelper.openSelectorStatus = false;
                try {
                    eval('cancelCallBack()');
                } catch (e) {

                }
            },
            buttons: buttons
        });
        $('#openDictionaryId').dialog('open');
        //可以调用到父类的方法
        /*var listFrame = $("#openDictionaryFrameId");
        listFrame.onload=function(){
        	alert("ok");
        	$(window.frames["openDictionaryFrameId"].document).find("body").focus();
//        	if(urlparams['initSearchData']=='N'){
//        		openDictionaryFrameId.xxxx('xxxxxxx');
//        	}
        	
        }*/
        var listFrame = $("#openDictionaryFrameId");
        listFrame.attr("src", url); 
        listFrame.load(function(){   //add by zhuJinJin 2016-03-22
        	//listFrame.contents().find("#search_customerName_cus").focus(); //客户名称默认获取焦点
        	listFrame.contents().find("input[type=text]").first().focus();
        	if(enter){
        		listFrame.contents().find("body").bind('keyup',function(event){
    				var keyValue = event.which;
    				if(keyValue == 13){
    					/*var jsonData=openDictionaryFrameId.getDictionarySelections();
    					console.info(jsonData);
    					if(jsonData && jsonData.length>0){
    						callBackjs(jsonData);
    						$('#openDictionaryId').dialog('close');
    					}*/
    				}
    			});
        	}
        });
        
        //下面代码可以解决2次去后台的问题，但是会出现函数找不到的新问题，导致订单明细添加不上商品
//      var openDictionaryFrameId = $("#openDictionaryFrameId");
//      var url=BASE_PATH + '/dictionaryController/toListPage?id=' + id+params;
//      openDictionaryFrameId.attr("src", url); 
//      openDictionaryFrameId.load();
      //document.getElementById('openDictionaryFrameId').focus();
    },
    openStockHistory: function (tableId, fieldName, index, currentRow, tabChooseId,formJson) {
    	
    	var productId = currentRow[fieldName];
    	//var currentRowJson = JSON.stringify(currentRow);
        //单书分析查询:tableId参数必须,fieldName参数必须(datagrid中绑定的属性名称),index参数必须(datagrid行下标),productId参数必须,companyId 非必须，如果为空的话，取当前登录人的公司
        if (!productId || productId == '') {
            alert('不存在商品ID');
        }
        $('#openStockHistoryId').parent().remove();
        /* var tmpDiv = '<div id="openStockHistoryId" class="easyui-dialog" closed="true" modal="true" resizable="true">' +
            '<iframe scrolling="no" id="openStockHistoryFrameId" name="openStockHistoryFrameId" frameborder="0" src="' +
            encodeURI(BASE_PATH + '/stockHistoryController/getPage?id=stockHistory&tableId=' + tableId + '&fieldName=' +
                fieldName + '&index=' + index + '&productId=' + productId + '&companyId=' + companyId + '&currentRowJson=' + currentRowJson) + '" ' +
            'style="width:90%;height:90%;"></iframe></div>';
        $(document.body).append(tmpDiv);
        $('#openStockHistoryId').dialog({
            collapsible: false,
            minimizable: false,
            maximizable: false,
            draggable: true,
            resizable: false,
            inline: true,
            shadow: false,
            title: '历史出入库',
            width: 985,
            height: 600,
            top: 2,
            modal: true,
            onResize: function (width, height) {
                $(this).find('iframe').width(width);
                $(this).find('iframe').height(height);
                $(this).find('iframe').attr('src', $(this).find('iframe').attr('src'));
            },
            buttons: [{
                text: '关闭',
                handler: function () {
                    $('#openStockHistoryId').dialog('close');
                }
            }]
        });
        $('#openStockHistoryId').dialog('open');*/
        //var parentQueryParams = getParamValues(pageDefaults.formId);
    	//var formJson = JSON.stringify(parentQueryParams);
        //console.info("formJson==========>" + formJson);
        var url = BASE_PATH + '/stockHistoryController/getPage?id=stockHistory&tableId=' + tableId + '&fieldName=' +
        		fieldName + '&index=' + index + '&productId=' + productId + '&tabChooseId=' + tabChooseId + '&formJson=' + formJson;
        if(productId.indexOf('.') > 0){
        	var proId = productId.substring(0,productId.indexOf('.')-1);
            var proId2 = productId.substring(productId.indexOf('.')+1,productId.length);
            productId = proId + proId2;
        }
        
        if(!isNull(currentRow['productName'])){
        	var productName = currentRow['productName'].substring(0,4);
    		MainTab.createTab(tableId+'_' + productId, '单书'+':'+productName, url); //打开一个新页面
    	}else if(!isNull(currentRow['PRODUCT_NAME'])){
    		var productName = currentRow['PRODUCT_NAME'].substring(0,4);
    		MainTab.createTab(tableId + productId, '单书'+':'+productName, url); //打开一个新页面
    	}else if(!isNull(currentRow['NAME'])){
    		var productName = currentRow['NAME'].substring(0,4);
    		MainTab.createTab(tableId + productId, '单书'+':'+productName, url); //打开一个新页面
    	}else if(!isNull(currentRow['name'])){
    		var productName = currentRow['name'].substring(0,4);
    		MainTab.createTab(tableId + productId, '单书'+':'+productName, url); //打开一个新页面
    	} else{
    		MainTab.createTab(tableId + productId, '单书', url); //打开一个新页面
    	}
    },
    openStockCustomerHistory: function (tableId, fieldName, index, currentRow, tabChooseId,formJson) {
    	var customerId = currentRow[fieldName];
        if (!customerId || customerId == '') {
            alert('不存在客户ID');
        }
        var url = BASE_PATH + '/stockCustomerHistoryController/getPage?id=stockCustomerHistory&tableId=' + tableId + '&fieldName=' +
        		fieldName + '&index=' + index + '&customerId=' + customerId + '&tabChooseId=' + tabChooseId + '&formJson=' + formJson;
        if(customerId.indexOf('.') > 0){
        	var cusId = customerId.substring(0,customerId.indexOf('.')-1);
            var cusId2 = customerId.substring(customerId.indexOf('.')+1,customerId.length);
            customerId = cusId + cusId2;
        }
        
        if(!isNull(currentRow['customerName'])){
        	var customerName = currentRow['customerName'].substring(0,4);
    		MainTab.createTab(tableId+'_' + customerId, '客户'+':'+customerName, url); //打开一个新页面
    	}else if(!isNull(currentRow['CUSTOMER_NAME'])){
    		var customerName = currentRow['CUSTOMER_NAME'].substring(0,4);
    		MainTab.createTab(tableId+'_' + customerId, '客户'+':'+customerName, url); //打开一个新页面
    	}else{
    		MainTab.createTab(tableId + customerId, '客户', url); //打开一个新页面
    	}
    },
    commonOpenStockHistory: function(tableId, fieldName, index, tabChooseId,formJson){
    	var currentRow = $('#' + tableId).datagrid('getRows')[index];
    	OasisHelper.openStockHistory(tableId, fieldName, index, currentRow, tabChooseId? tabChooseId:0,formJson?formJson:'');
	},
    commonOpenStockCustomerHistory: function(tableId, fieldName, index, tabChooseId,formJson){
    	var currentRow = $('#' + tableId).datagrid('getRows')[index];
    	OasisHelper.openStockCustomerHistory(tableId, fieldName, index, currentRow, tabChooseId? tabChooseId:0,formJson?formJson:'');
	}
};

//通用选择器按键事件绑定
$(document).on('keyup', 'input[oasisType="selector"]', function (e) {
    var key = e.which;
    var obj = this;
    if (key == 13) {
    	var inputObj = obj;
        var curSelectorInput = $(this);
        var searchValue = $(this).val();
        var oasisOptions = $(this).attr("oasisOptions");
        var options = eval('(' + oasisOptions + ')');
        console.log(options);
        var isOpenSelector = true;
        if (searchValue != '' && options != '') {
            $(this).attr('disabled', true);
            var parentWidth = 0;
            var parentHeight = 0;
            if(options.width && options.height){
            	parentWidth = options.width;
            	parentHeight = options.height;
            	//options.width = 800;
            	//options.height = 500;
            }
            var defaults = {'width': 800, 'height': 500, 'callBack': $.noop(), 'urlparams': '','noDataMsg':'未查询到数据，请重新录入查询条件！'};
            var settings = $.extend({}, defaults, options);
            var urlparams = settings['urlparams'];
            var id = settings['id'];
            var width=defaults['width'];
            var callBackjs = settings['callBack'];
            var params={};
            params['oasis_search_fuzzy']=searchValue;
            var callBackParams = settings['callBackParams'];
            //var paramObject=callBackParams.call(callBackParams);
            var paramObject = {};
            if(callBackParams && (typeof callBackParams == "function")){
            	paramObject=callBackParams.call(callBackParams);
            }
            for(var key in  paramObject){
            	params[key]=paramObject[key];
            }
            var noDataMsg=settings['noDataMsg'];
            $.ajax({
                type: "post",// 
                dataType: "json",// 返回json格式的数据
                url: BASE_PATH + '/dictionaryController/quickSearch?id=' + id,// 要访问的后台地址
                data: params,
                success: function (data) {// msg为返回的数据，在这里做数据绑定
                    $(curSelectorInput).removeAttr('disabled');
                    if (data.rs == 1) {
                        callBackjs.call(callBackjs, data.datas, callBackParams);
                    } else if (data.rs == 0) {
                        jQuery.messager.alert('提示:',noDataMsg);
                    } else if (data.rs == 2) {
                    	options.urlparams = params;
                    	options.callBackParams=undefined;
                    	if(parentWidth > 0 && parentHeight > 0){
                    		if(typeof window.parent.changeIframeSize == "function"){
                        		window.parent.changeIframeSize(parentWidth, parentHeight, $(inputObj).attr('id'));
                    		}
                    	}
                        OasisHelper.openSelector(options);
                    } else {
                        alert('请通知管理员，查询错误！');
                    }
                },
                error: function () {
                    $(curSelectorInput).removeAttr('disabled');
                    alert('请通知管理员，查询错误！');
                }
            });
        }
    }
});
/**
 * ajax请求
 * @param opts
 * @param url
 * @param success
 * @param error
 */
function redisDataLoader(opts, url, success, error) {
    $.ajax({
        url: url,
        dataType: 'text',
        data: opts.params,
        async: false,
        success: function (data) {
            success(data);
        },
        error: function () {
            console.log("查询失败");
            error.apply(this, arguments);
        }
    });
}


